package com.heima.app.gateway.filter;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//import com.heima.wemedia.gateway.utils.AppJwtUtil;

@Component             //包扫描注解
@Order(1)           //过滤器执行顺序注解
@Slf4j
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        /*获取请求与响应对象，获取url，登录则放行*/
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (path.contains("/login")) {
            /*放行*/
            return chain.filter(exchange);
        }
        /*查看request对象的header中有没有TOKEN，没有就拦截*/
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        /*3校验TOKEN是否正确*/
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int verifyToken = AppJwtUtil.verifyToken(claims);
            if (verifyToken > 0) {//token失效
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            /*解析TOKEN，获取登陆用户的ID*/
            Integer id = claims.get("id", Integer.class);
            log.info("header token id:{}, URL:{}", id, request.getURI().getPath());
            /*将ID下放到各个微服务的header中*/
            ServerHttpRequest httpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", String.valueOf(id));
            }).build();
            exchange.mutate().request(httpRequest).build();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("verifytoken is error ,url:{}", path);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        /*放行*/
        return chain.filter(exchange);
    }
}
